# coding: utf-8
from json import dump, loads
from pathlib import Path
from typing import Union

from pandas import DataFrame

from .engin_base import FileEngineBase, ApiJsonTemplate, UiJsonTemplate


class JsonEngine(FileEngineBase):
    def _openDataFrame(self, sheet_name: str = None) -> DataFrame:
        with open(self.fileName, 'r', encoding=self.encoding) as fp:
            data = fp.read()
            if data:
                return DataFrame(loads(data))
            else:
                return DataFrame()

    @classmethod
    def write(cls, data: Union[list, dict], fileName: Union[str, Path] = None):
        if fileName is None:
            fileName = cls.fileName
        with open(fileName, 'w', encoding=cls.encoding) as fp:
            dump(data, fp, indent=4, ensure_ascii=False, sort_keys=False)

    @classmethod
    def ApiTemplate(cls, fileName: Union[str, Path]):
        cls.to_json(ApiJsonTemplate, fileName=fileName)

    @classmethod
    def UiTemplate(cls, fileName: Union[str, Path]):
        cls.write(UiJsonTemplate, fileName=fileName)


def json_write(data: Union[list, dict], fileName: Union[str, Path] = None):
    """
    write data to json
    :param data:
    :param fileName:
    :return:
    """
    if isinstance(fileName, str):
        fileName = Path(fileName)
    fileName.parent.mkdir(parents=True, exist_ok=True)
    fileName.touch(exist_ok=True)
    with fileName.open('r', encoding='utf-8') as fp:
        rd = fp.read()
        if rd:
            low_data = loads(rd)
        else:
            low_data = {}
    low_data.update(data)
    with fileName.open('w', encoding='utf-8') as fp:
        dump(low_data, fp, indent=2, ensure_ascii=False, sort_keys=False)


def json_read(fileName: Union[str, Path]) -> dict:
    try:
        with open(fileName, 'r', encoding='utf-8') as fp:
            return loads(fp.read())
    except Exception:
        return {}
